<template>
  <div>
    <Input
      class="margin"
      v-model="rootName"
      placeholder="请输入根节点名字"
      clearable
      style="width: auto"
      @on-enter="addroot"
    />
    <Button type="primary" @click="addroot">添加根节点</Button>
    <Input
      class="margin"
      v-model="childName"
      placeholder="请输入子节点名字"
      clearable
      style="width: auto"
    />

    <!-- 删除时触发的对话框 -->
    <div>
      <!-- 删除文章,文档 -->
      <Modal v-model="dilLog_del_ari" width="360">
        <template #header>
          <p style="color: #f60; text-align: center">
            <Icon type="ios-information-circle"></Icon>
            <span>是否确定删除该文章!</span>
          </p>
        </template>

        <div style="text-align: center">
          <p>请选择操作</p>
        </div>
        <template #footer>
          <div>
            <Button @click="dilLog_del_ari = false">取消</Button>
            <Button type="error" @click="fun_dilLog_del_ari">确认删除</Button>
          </div>
        </template>
      </Modal>
      <!-- 删除子节点 -->
      <Modal v-model="dilLog_del_ari_rec_chi" width="360">
        <template #header>
          <p style="color: #f60; text-align: center">
            <Icon type="ios-information-circle"></Icon>
            <span>是否确定删除该文件夹!</span>
          </p>
        </template>

        <div style="text-align: center">
          <p>请选择操作</p>
        </div>
        <template #footer>
          <div>
            <Button @click="dilLog_del_ari_rec_chi = false">取消</Button>
            <Button type="error" @click="fun_dilLog_del_ari_rec_chi"
              >确认删除</Button
            >
          </div>
        </template>
      </Modal>
      <!-- 删除根节点 -->
      <Modal v-model="dilLog_del_ari_rec_root" width="360">
        <template #header>
          <p style="color: #f60; text-align: center">
            <Icon type="ios-information-circle"></Icon>
            <span>是否确定删除该文件夹!</span>
          </p>
        </template>

        <div style="text-align: center">
          <p>请选择操作</p>
        </div>
        <template #footer>
          <div>
            <Button @click="dilLog_del_ari_rec_root = false">取消</Button>
            <Button type="error" @click="fun_dilLog_del_ari_rec_root"
              >确认删除</Button
            >
          </div>
        </template>
      </Modal>
    </div>

    <Tree
      :data="data5"
      :render="renderContent"
      class="demo-tree-render margin"
      @on-contextmenu="handleContextMenu"
      expand-node
    >
      <template #contextMenu>
        <DropdownItem v-on:click="rearrange(contextData, data5, -1)"
          >↑</DropdownItem
        >
        <DropdownItem v-on:click="rearrange(contextData, data5, 1)"
          >↓</DropdownItem
        >
        <DropdownItem v-on:click="handleContextMenuEdit">重命名</DropdownItem>
        <DropdownItem v-on:click="paste_node(contextData)"
          >粘贴到此</DropdownItem
        >
        <DropdownItem
          v-on:click="copy_node(null, null, contextData, 'move', true)"
          >移动</DropdownItem
        >
        <DropdownItem
          v-on:click="copy_node(null, null, contextData, 'copy', true)"
          >复制</DropdownItem
        >
        <DropdownItem
          v-on:click="handleContextMenuDelete"
          style="color: #ed4014"
          >删除</DropdownItem
        >
      </template></Tree
    >
  </div>
</template>
<script>
// oss 操作
import putBuffer from '@/api/API_Uploading_Directory_Tree'
// 节点类型
import {
  nodeType_children_node,
  nodeType_root_node,
  nodeType_pdf,
  nodeType_article,
  art_html_1,
  art_html_2
} from '@/mylibs/define'
// event bus
import eventbus from '@/eventBus/eventbus'

// render
import { renderContent } from '@/mylibs/node_render'

import { resolveComponent } from 'vue'
import { getUuid } from '@/mylibs/functions'

import FileSaver from 'file-saver'
export default {
  // vue3
  emits: ['click'],
  props: ['PATH_Article_editor_data', 'PATH_Directory_tree','edit_document_routePath','edit_article_routePath'],
  data() {
    return {
      data5: [],
      buttonProps: {
        type: 'default',
        size: 'small'
      },
      contextData: null,
      rootName: '',
      childName: '',
      footer: 'footer',
      need_edit_art: null,
      need_edit_doc: null,
      remove_data: null,
      // oss删除文章--对话框
      dilLog_del_ari: false,
      // 递归删除文件夹(子)中的文章--对话框
      dilLog_del_ari_rec_chi: false,
      // 递归删除文件夹(根)中的文章--对话框
      dilLog_del_ari_rec_root: false,
      // 剪切,复制的节点
      copy_data: {
        root: null,
        node: null,
        data: null,
        // move copy
        type: '',
        is_root_data: false
      },

      // 根节点渲染函数
      root_render: (h, { root, node, data }) => {
        return h(
          'span',
          {
            style: {
              display: 'inline-block',
              width: '100%'
            }
          },
          [
            h('span', [
              // vue3
              h(resolveComponent('Icon'), {
                type: 'ios-folder-outline',
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ]),
            h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  float: 'right',
                  marginRight: '8px'
                }
              },
              [
                h(resolveComponent('Button'), {
                  // vue3
                  ...this.buttonProps,
                  icon: 'ios-arrow-round-up',
                  title: '上移',

                  style: {
                    width: '64px',
                    marginRight: '8px'
                  },
                  // vue3
                  onClick: (e) => {
                    this.rearrange(data, this.data5, -1, e)
                  }
                }),
                // vue3
                h(resolveComponent('Button'), {
                  // vue3
                  ...this.buttonProps,
                  icon: 'ios-arrow-round-down',
                  title: '下移',

                  style: {
                    width: '64px',
                    marginRight: '8px'
                  },
                  // vue3
                  onClick: (e) => {
                    this.rearrange(data, this.data5, 1, e)
                  }
                }),

                h(resolveComponent('Button'), {
                  // vue3
                  ...this.buttonProps,
                  icon: 'ios-add',
                  title: '添加子节点',

                  style: {
                    width: '64px',
                    marginRight: '0px'
                  },
                  // vue3
                  onClick: (e) => {
                    this.append(data, e)
                  }
                })
              ]
            )
          ]
        )
      },

      // 子节点样式
      children_render: (h, { root, node, data }) => {
        return h(
          'span',
          {
            style: {
              display: 'inline-block',
              width: '100%'
            }
          },
          [
            h('span', [
              h(resolveComponent('Icon'), {
                type: 'md-folder',
                style: {
                  marginRight: '8px'
                }
              }),
              h('span', data.title)
            ]),
            h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  float: 'right',
                  marginRight: '0'
                }
              },
              [
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-arrow-round-up',
                  title: '上移',
                  style: {
                    marginRight: '8px'
                  },
                  onClick: (e) => {
                    this.rearrange(data, this.data5, -1, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-arrow-round-down',
                  title: '下移',
                  style: {
                    marginRight: '8px'
                  },
                  onClick: (e) => {
                    this.rearrange(data, this.data5, 1, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-add',
                  title: '添加子节点',
                  style: {
                    marginRight: '8px'
                  },
                  onClick: (e) => {
                    this.append(data, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-remove',
                  title: '删除',

                  style: {
                    marginRight: '8px'
                  },
                  onClick: (e) => {
                    this.remove(root, node, data, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-brush',
                  title: '重命名',
                  style: { marginRight: '8px' },
                  onClick: (e) => {
                    this.edit(root, node, data, e)
                  }
                }),
                // 粘贴,复制,移动按钮
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'ios-clipboard-outline',
                  title: '粘贴到此',
                  style: { marginRight: '8px' },
                  onClick: (e) => {
                    this.paste_node(data, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  title: '移动',
                  icon: 'ios-move',
                  style: { marginRight: '8px' },
                  onClick: (e) => {
                    this.copy_node(root, node, data, 'move', false, e)
                  }
                }),
                h(resolveComponent('Button'), {
                  ...this.buttonProps,
                  icon: 'md-copy',
                  title: '复制',
                  style: { marginRight: '8px' },
                  onClick: (e) => {
                    this.copy_node(root, node, data, 'copy', false, e)
                  }
                })
              ]
            )
          ]
        )
      },

      renderContent
    }
  },

  // 监听器
  watch: {
  },

  // vue方法
  methods: {
    // 消息提示
    info(desc) {
      this.$Notice.info({
        title: '注意!',
        desc
      })
    },

    //递归目录树数据,设置不同样式
    Recursive_directory_tree(dirData) {
      for (let index = 0; index < dirData.length; index++) {
        const element = dirData[index]
        // 设置根文章节点样式
        if (element.node_type && element.node_type == nodeType_article) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-paper-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title),
                  h(
                    'span',
                    {
                      style: {
                        marginLeft: '10px',
                        color: 'red'
                      }
                    },
                    ['[' + data.upload.permission + ']']
                  )
                ]),
                h(
                  'span',
                  {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '0'
                    }
                  },
                  [
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-arrow-round-up',
                      title: '上移',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.rearrange(data, this.data5, -1, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-arrow-round-down',
                      title: '下移',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.rearrange(data, this.data5, 1, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-cloud-download-outline',
                      style: {
                        marginRight: '8px'
                      },
                      title: '下载',
                      onClick: (e) => {
                        this.down_art(data, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-create-outline',
                      title: '编辑',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.edit_article(data, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-backspace-outline',
                      title: '删除',
                      style: { marginRight: '8px' },
                      onClick: (e) => {
                        this.delete_Oss_Article(root, node, data, e)
                      }
                    }),
                    // 复制,移动按钮
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-move',
                      style: { marginRight: '8px' },
                      title: '移动',
                      onClick: (e) => {
                        this.copy_node(root, node, data, 'move', false, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'md-copy',
                      title: '复制',
                      style: { marginRight: '8px' },
                      onClick: (e) => {
                        this.copy_node(root, node, data, 'copy', false, e)
                      }
                    })
                  ]
                )
              ]
            )
          }
        }
        // pdf
        if (element.node_type && element.node_type == nodeType_pdf) {
          element['render'] = (h, { root, node, data }) => {
            return h(
              'span',
              {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              },
              [
                h('span', [
                  h(resolveComponent('Icon'), {
                    type: 'ios-leaf-outline',
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title),
                  h(
                    'span',
                    {
                      style: {
                        marginLeft: '10px',
                        color: 'red'
                      }
                    },
                    ['[' + data.upload.permission + ']']
                  )
                ]),
                h(
                  'span',
                  {
                    style: {
                      display: 'inline-block',
                      float: 'right',
                      marginRight: '0'
                    }
                  },
                  [
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-arrow-round-up',
                      title: '上移',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.rearrange(data, this.data5, -1, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-arrow-round-down',
                      title: '下移',
                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.rearrange(data, this.data5, 1, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-cloud-download-outline',
                      style: {
                        marginRight: '8px'
                      },
                      title: '下载',
                      onClick: (e) => {
                        this.down_document(data, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-create-outline',
                      title: '编辑',

                      style: {
                        marginRight: '8px'
                      },
                      onClick: (e) => {
                        this.edit_document(data, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-backspace-outline',
                      style: { marginRight: '8px' },
                      title: '删除',

                      onClick: (e) => {
                        this.delete_Oss_Article(root, node, data, e)
                      }
                    }),
                    // 复制,移动按钮
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'ios-move',
                      style: { marginRight: '8px' },
                      title: '移动',

                      onClick: (e) => {
                        this.copy_node(root, node, data, 'move', false, e)
                      }
                    }),
                    h(resolveComponent('Button'), {
                      ...this.buttonProps,
                      icon: 'md-copy',
                      style: { marginRight: '8px' },
                      title: '复制',

                      onClick: (e) => {
                        this.copy_node(root, node, data, 'copy', false, e)
                      }
                    })
                  ]
                )
              ]
            )
          }
        }

        // 子文件夹样式
        if (element.node_type && element.node_type == nodeType_children_node) {
          element['render'] = this.children_render
        }

        // 根文件夹样式
        if (element.node_type && element.node_type == nodeType_root_node) {
          element['render'] = this.root_render
        }

        if (element.children && element.children.length != 0) {
          // 子文件夹
          this.Recursive_directory_tree(element.children)
        }
      }
    },

    // 删除文章,文档
    delete_Oss_Article(root, node, data, e) {
      e.stopPropagation()

      this.remove_data = {
        root,
        node,
        data
      }

      this.dilLog_del_ari = true
    },

    // 对话框确认删除
    async fun_dilLog_del_ari() {
      console.log('test')
      this.dilLog_del_ari = false

      var root = this.remove_data.root,
        node = this.remove_data.node,
        data = this.remove_data.data

      var path = data.upload.bucket_filepath
      let { ok, err } = await putBuffer('del', path)
      if (ok) {
        this.$Notice.success({ desc: '删除文章,文档成功' })

        try {
          // 还要从目录树中删除
          const parentKey = root.find((el) => el === node).parent
          const parent = root.find((el) => el.nodeKey === parentKey).node
          const index = parent.children.indexOf(data)
          parent.children.splice(index, 1)

          // 保存目录树到oss
          this.saveDataDir()
          this.$Notice.success({ desc: '从目录树中删除成功' })
        } catch (e) {
          this.$Notice.error({ desc: '从目录树中删除失败:' + e })
        }
      } else {
        this.$Notice.error({ desc: '删除文章,文档失败:' + err })
      }
    },

    // 递归删除文件夹中的文章,文档
    async delete_Oss_Article_recursively(dirNode, is_first, fun_success) {
      var success = true

      for (let index = 0; index < dirNode.children.length; index++) {
        var element = dirNode.children[index]
        if (
          element.node_type == nodeType_article ||
          element.node_type == nodeType_pdf
        ) {
          let { ok, err } = await putBuffer(
            'del',
            element.upload.bucket_filepath
          )
          if (ok) {
          } else {
            this.$Notice.error({ desc: '删除文章,文档失败:' + err })
            success = false
          }
        }

        if (element.children && element.children.length != 0) {
          let ok = await this.delete_Oss_Article_recursively(element)
          if (!ok) {
            success = false
          }
        }
      }

      if (is_first) {
        if (success) {
          if (fun_success) {
            fun_success()
          }
        }
      }

      return success
    },

    // 添加子节点(子文件夹)
    append(data, e) {
      e.stopPropagation()
      var name = this.childName
      if (name.length == 0) {
        this.info('子节点名字为空!')
        return
      }
      var children = data.children || []
      children.push({
        title: name,
        mynodeKey: getUuid(),
        expand: true,
        node_type: nodeType_children_node,
        render: this.children_render,
        children: []
      })
      data.children = children

      // 保存目录树到oss
      this.saveDataDir()
    },

    // 删除子节点
    remove(root, node, data, e) {
      e.stopPropagation()
      this.remove_data = {
        root,
        node,
        data
      }
      this.dilLog_del_ari_rec_chi = true
    },

    // 对话框确认删除
    async fun_dilLog_del_ari_rec_chi() {
      this.dilLog_del_ari_rec_chi = false

      var root = this.remove_data.root,
        node = this.remove_data.node,
        data = this.remove_data.data
      try {
        // 删除文件夹中的文章
        var ok = await this.delete_Oss_Article_recursively(data, true)
      } catch (e) {
        this.$Notice.error({ desc: '删除文章,文档失败:' + e })
      }

      if (ok) {
        this.$Notice.success({ desc: '删除文章,文档成功' })

        try {
          // 目录树
          const parentKey = root.find((el) => el === node).parent
          const parent = root.find((el) => el.nodeKey === parentKey).node
          const index = parent.children.indexOf(data)
          parent.children.splice(index, 1)
          this.$Notice.success({ desc: '从目录树中删除成功' })
          // 保存目录树到oss
          this.saveDataDir()
        } catch (e) {
          this.$Notice.error({ desc: '从目录树中删除失败:' + e })
        }
      }
    },

    // 重命名子节点
    edit(root, node, data, e) {
      e.stopPropagation()
      var name = this.childName
      if (name.length == 0) {
        this.info('子节点名字为空!')
        return
      }
      data.title = name

      // 保存目录树到oss
      this.saveDataDir()
    },

    // 添加根节点
    addroot() {
      // 判断输入是否为空
      var name = this.rootName
      if (name.length == 0) {
        this.info('根节点名字为空!')
        return
      }
      // 判断是否重名
      // var bo_isrepeat = false
      // for (let index = 0; index < this.data5.length; index++) {
      //   const element = this.data5[index]
      //   if (element.title == name) {
      //     var bo_isrepeat = true
      //     this.info('根节点名字不可重复!')
      //     break
      //   }
      // }

      this.data5.push({
        title: name,
        mynodeKey: getUuid(),
        node_type: nodeType_root_node,
        // 开启右击
        contextmenu: true,
        expand: true,
        render: this.root_render,
        children: []
      })

      // 保存目录树到oss
      this.saveDataDir()
    },

    // 右击处理函数
    handleContextMenu(data, event, position) {
      // 引用
      this.contextData = data
    },

    // 重命名根节点
    handleContextMenuEdit() {
      var name = this.rootName
      if (name.length == 0) {
        this.info('根节点名字为空!')
        return
      }
      this.contextData.title = name
      // 保存目录树到oss
      this.saveDataDir()
    },

    // 删除根节点
    handleContextMenuDelete() {
      this.dilLog_del_ari_rec_root = true
    },

    // 对话框确认删除
    async fun_dilLog_del_ari_rec_root() {
      this.dilLog_del_ari_rec_root = false

      try {
        var ok = await this.delete_Oss_Article_recursively(
          this.contextData,
          true
        )
      } catch (e) {
        this.$Notice.error({ desc: '删除文章,文档失败:' + e })
      }

      if (ok) {
        this.$Notice.success({ desc: '删除文章,文档成功' })
        try {
          var newlist = []
          newlist = this.data5.filter((item) => {
            return item.mynodeKey != this.contextData.mynodeKey
          })
          this.data5 = newlist
          this.$Notice.success({ desc: '从目录树中删除成功' })
          // 保存目录树到oss
          this.saveDataDir()
        } catch (e) {
          this.$Notice.error({ desc: '从目录树中删除失败:' + e })
        }
      }
    },

    // 获取目录树数据
    async getDirTreeData(fun_back) {
      var { ok, res, err } = await putBuffer('get', this.PATH_Directory_tree)
      if (ok) {
        if (res) {
          if (Array.isArray(res)) {
            this.data5 = res
            this.Recursive_directory_tree(this.data5)
            if (fun_back) {
              fun_back()
            }
          } else {
            this.$Notice.info('数据非数组')
          }
        }
      } else {
        this.$Notice.error({ desc: '获取目录树数据失败:' + err })
      }
    },

    // 提交数据到阿里云oss
    saveDataDir(newdata) {
      var data = this.data5
      if (newdata) {
        data = newdata
      }
      putBuffer('put', this.PATH_Directory_tree, data).then(
        ({ res, ok, err }) => {
          if (ok) {
            console.log('目录树管理--保存了目录树')
          } else {
            this.$Notice.error({ desc: '目录树保存失败:' + err })
          }
        }
      )
    },

    // 编辑文章
    edit_article(data, e) {
      e.stopPropagation()
      e.preventDefault()
      this.need_edit_art = data

      // 路由跳转
      this.$router.push(this.edit_article_routePath)
      // 等待组件创造,激活,再发送数据
    },

    // 编辑文档
    edit_document(data, e) {
      e.stopPropagation()
      this.need_edit_doc = data

      this.$router.push(this.edit_document_routePath)
      // 等待组件创造,激活,再发送数据
    },

    async down_art(data, e) {
      this.$Notice.info({ desc: '正在请求数据，请耐心等待' })
      e.stopPropagation()
      let { ok, err, res } = await putBuffer(
        'get',
        data.upload.bucket_filepath,
        null,
        false
      )
      if (ok) {
        let html = art_html_1 + res.editor_data + art_html_2
        let name = data.title + '.html'
        let file = new File([html], name)
        FileSaver.saveAs(file, name)
      } else {
        this.$Notice.error({ desc: err })
      }
    },

    // 下载文档
    async down_document(data, e) {
      this.$Notice.info({ desc: '正在请求数据，请耐心等待' })
      e.stopPropagation()
      let { ok, err, res } = await putBuffer(
        'get',
        data.upload.bucket_filepath,
        null,
        true
      )
      if (ok) {
        if (data.title.indexOf('.pdf') != -1) {
          var name = data.title
        } else {
          var name = data.title + '.pdf'
        }
        let file = new File([res], name)
        FileSaver.saveAs(file, name)
      } else {
        this.$Notice.error({ desc: err })
      }
    },

    // 复制,移动
    copy_node(root, node, data, type, is_root, e) {
      if (e) {
        e.stopPropagation()
      }
      this.copy_data.node = node
      this.copy_data.type = type
      this.copy_data.data = data
      this.copy_data.root = root
      this.copy_data.is_root_data = is_root
      if (type == 'move') {
        this.$Notice.success({ desc: '已经剪切好了' })
      }
      if (type == 'copy') {
        this.$Notice.success({ desc: '已经复制好了' })
      }
    },

    is_copy_to_son(father_node, node) {
      var bo = false
      if (father_node.mynodeKey == node.mynodeKey) return true
      try {
        for (var index = 0; index < node.children.length; index++) {
          var element = node.children[index]
          if (element.node_type == nodeType_children_node) {
            if (element.mynodeKey == father_node.mynodeKey) {
              bo = true
              break
            }

            var bo1 = this.is_copy_to_son(father_node, element)
            if (bo1) {
              bo = true
              break
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
      return bo
    },

    // 文件夹改变mynodeKey
    async change_mynodeKey(node) {
      node.mynodeKey = getUuid()
      // 文件夹下的文章,文档的father_nodeKey也要改变
      if (node.node_type == nodeType_children_node)
        for (let index = 0; index < node.children.length; index++) {
          const element = node.children[index]
          if (
            element.node_type == nodeType_article ||
            element.node_type == nodeType_pdf
          ) {
            element.mynodeKey = getUuid()
            element.father_nodeKey = node.mynodeKey

            // 复制oss编辑器数据
            let is_file = true
            if (element.node_type == nodeType_pdf) {
              is_file = true
            } else {
              is_file = false
            }
            let { ok, err, res } = await putBuffer(
              'get',
              element.upload.bucket_filepath,
              null,
              is_file
            )

            if (ok) {
              let path = this.PATH_Article_editor_data + getUuid()
              let { ok, err } = await putBuffer('put', path, res, is_file)
              if (ok) {
                element.upload.bucket_filepath = path
              } else {
                this.$Notice.error({ desc: '提交编辑器数据失败:' + err })
              }
            } else {
              this.$Notice.error({ desc: '获取编辑器数据失败:' + err })
            }
          }

          if (element.node_type == nodeType_children_node) {
            await this.change_mynodeKey(element)
          }
        }
    },

    // 粘贴
    async paste_node(father_node, e) {
      if (e) {
        e.stopPropagation()
      }
      if (!this.copy_data || !this.copy_data.data) {
        this.$Notice.info({ desc: '请先复制剪切 文件或者文件夹' })
        return
      }

      if (this.is_copy_to_son(father_node, this.copy_data.data)) {
        this.$Notice.info({ desc: '不能复制移动到它的子节点' })
        return
      }

      // 深拷贝对象
      var str = JSON.stringify(this.copy_data.data)
      var obj = JSON.parse(str)

      if (obj.node_type == nodeType_root_node) {
        obj.node_type = nodeType_children_node
        obj.contextmenu = false
      }
      console.log(obj)
      try {
        if (this.copy_data.type == 'copy') {
          // 改变mynodeKey
          if (
            obj.node_type == nodeType_article ||
            obj.node_type == nodeType_pdf
          ) {
            obj.mynodeKey = getUuid()
            obj.father_nodeKey = father_node.mynodeKey

            // 复制oss编辑器数据
            let is_file = true
            if (obj.node_type == nodeType_pdf) {
              is_file = true
            } else {
              is_file = false
            }
            let { ok, err, res } = await putBuffer(
              'get',
              obj.upload.bucket_filepath,
              null,
              is_file
            )

            if (ok) {
              let path = this.PATH_Article_editor_data + getUuid()
              let { ok, err } = await putBuffer('put', path, res, is_file)
              if (ok) {
                obj.upload.bucket_filepath = path
              } else {
                this.$Notice.error({ desc: '提交编辑器数据失败:' + err })
              }
            } else {
              this.$Notice.error({ desc: '获取编辑器数据失败:' + err })
            }
          }

          if (
            obj.node_type == nodeType_children_node ||
            obj.node_type == nodeType_root_node
          ) {
            await this.change_mynodeKey(obj)
          }

          father_node.children.push(obj)
          this.$Notice.success({ desc: '复制成功' })
          // 保存目录树到oss
          this.saveDataDir()
          this.Recursive_directory_tree(this.data5)
          // this.copy_data.data = null
        }
      } catch (e) {
        this.$Notice.error({ desc: '复制失败:' + e })
      }

      try {
        if (this.copy_data.type == 'move') {
          var bo_ok = true
          // 删除
          try {
            if (this.copy_data.is_root_data) {
              this.data5.splice(this.data5.indexOf(this.copy_data.data), 1)
            } else {
              var root = this.copy_data.root,
                node = this.copy_data.node,
                data = this.copy_data.data
              const parentKey = root.find((el) => el === node).parent
              const parent = root.find((el) => el.nodeKey === parentKey).node
              const index = parent.children.indexOf(data)
              parent.children.splice(index, 1)
            }
          } catch (e) {
            this.$Notice.error({ desc: '移动失败--删除失败:' + e })
            console.log(e)
            var bo_ok = false
          }

          if (bo_ok) {
            // 移动  不需要改变mynodeKey
            // 添加
            father_node.children.push(obj)
            this.$Notice.success({ desc: '移动成功' })
            this.copy_data.data = null
            // 保存目录树到oss
            this.saveDataDir()
            this.Recursive_directory_tree(this.data5)
          }
        }
      } catch (e) {
        this.$Notice.error({ desc: '移动失败--添加失败:' + e })
        console.log(e)
      }
    },

    // 调整节点顺序
    rearrange(node, array, addPosNum, e) {
      if (e) {
        e.stopPropagation()
      }
      for (let index = 0; index < array.length; index++) {
        const element = array[index]
        if (element.mynodeKey == node.mynodeKey) {
          let pos = array.indexOf(node)
          if (pos + addPosNum < 0 || pos + addPosNum > array.length - 1) {
            this.$Notice.info({ desc: '超出了范围' })
          } else {
            // 删除
            array.splice(pos, 1)
            // 添加
            pos += addPosNum
            array.splice(pos, 0, node)
            // 保存
            this.saveDataDir()
          }

          return 0
        }

        if (
          element.node_type == nodeType_children_node ||
          element.node_type == nodeType_root_node
        ) {
          let res = this.rearrange(node, element.children, addPosNum)
          if (res == 0) {
            return 0
          }
        }
      }
    }
  },

  //生命周期函数
  created() {
    console.log('文章 目录树组件 创造')
    eventbus.on('ev_art_active', () => {
      eventbus.emit('need_edit', this.need_edit_art)
    })

    eventbus.on('ev_upload_active', () => {
      eventbus.emit('need_edit_document', this.need_edit_doc)
    })
   
  },

  // 激活该路由组件时调用
  activated() {
    // 文章组件 激活
    console.log('文章 目录树组件 激活')

    this.getDirTreeData()
  },

  deactivated() {
    // 文章组件 缓存
  }
}
</script>
<style>
.demo-tree-render .ivu-tree-title {
  width: 100%;
}

.margin {
  margin: 10px 10px;
}

.padding {
  padding: 10px 10px;
}
</style>
